package com.ywgt;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 稀疏数组
 */
public class ParseArray{
    public static void main(String[] args) throws Exception{
        //二维数组
        int[] [] array=new int[12][12];
        array[1][2]=1;
        array[2][3]=2;

        for (int[] row:array){
            for(int data:row){
                System.out.print("\t"+data);
            }
            System.out.println();
        }
        int hasData=0;
        for (int[] ints : array) {
            for (int anInt : ints) {
                if(anInt!=0){
                    hasData++;
                }
            }
        }
        //稀疏数组方案
        int [][] parseArray=new int[hasData+1][3];
        parseArray[0][0]=12;
        parseArray[0][1]=12;
        parseArray[0][2]=3;
        int n=1;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if(array[i][j]!=0){
                    parseArray[n][0]=i;
                    parseArray[n][1]=j;
                    parseArray[n][2]=array[i][j];
                    n++;
                }
            }
        }
        for (int[] row:parseArray){
            for(int data:row){
                System.out.print("\t"+data);
            }
            System.out.println();
        }
        File file=new File("array.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        OutputStream outputStream=new FileOutputStream(file,true);
        for (int[] row:parseArray){
            for(int data:row){
                outputStream.write(String.valueOf(data+" ").getBytes(StandardCharsets.UTF_8));
            }
            outputStream.write("\n".getBytes(StandardCharsets.UTF_8));
        }
        outputStream.close();
        //还原二维数组
        int[][] parse=new int[parseArray[0][0]][parseArray[0][1]];
        for (int i = 1; i < parseArray.length; i++) {
            parse[parseArray[i][0]][parseArray[i][1]]=parseArray[i][2];
        }
        for (int[] row:parse){
            for(int data:row){
                System.out.print("\t"+data);
            }
            System.out.println();
        }
    }
}
